package com.hn658.groupshare.backend.servlet;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.hn658.framework.logging.enums.LogCategory;
import com.hn658.framework.shared.constants.CommonConstants;
import com.hn658.framework.shared.context.UserContext;
import com.hn658.groupshare.backend.util.AuthCookieEditor;
import com.hn658.groupshare.common.constants.BaseGroupShareContants;
import com.hn658.groupshare.common.entity.UserInfoEO;
import com.hn658.groupshare.core.service.IAuthentication;
import com.hn658.groupshare.core.service.ISessionService;
import com.hn658.groupshare.core.service.IUserInfoService;

/**
 * 登录的servlet
 * 
 * @ClassName: LoginServlet
 * @author ztjie
 * @date 2014年9月2日 下午2:46:23
 */
public class LoginServlet extends AbstractServlet {

	private static final long serialVersionUID = 3599960399642760403L;

	private IUserInfoService userInfoService;
	private ISessionService sessionManager;
	private IAuthentication authentication;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		userInfoService = ac.getBean(IUserInfoService.class);
		sessionManager = ac.getBean(ISessionService.class);
		authentication = ac.getBean(IAuthentication.class);
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String loginAccount = req.getParameter("loginAccount");
		String password = req.getParameter("password");
		String authkey = (String) req.getSession().getAttribute(
				CommonConstants.SERVICE_REQUEST_HEADER_AUTHKEY);
		if (loginAccount == null && password == null) {
			if (authkey != null) {
				UserInfoEO user = (UserInfoEO) sessionManager
						.getUserByAuthkey(authkey);
				if (user != null) {
					forwardIndex(req, resp);
					return;
				}
			}
			forwardLogin(req, resp);
			return;
		}

		// 根据账号查找用户信息
		UserInfoEO userInfo = userInfoService.findUserByAccount(StringUtils
				.lowerCase(StringUtils.trim(loginAccount)));

		if (null == userInfo) {
			// 用户账号不存在
			errorMsg(req, "用户账号不存在");
			forwardLogin(req, resp);
			return;
		}
		if (userInfo.getIsDeleted()) {
			// 用户已经被禁用
			errorMsg(req, "用户已经被禁用");
			forwardLogin(req, resp);
			return;
		}
		if (!authentication.authenticate(userInfo.getLoginAccount(),
				userInfo.getPassword(), password)) {
			// 如果用户登录名密码不匹配设置密码错误
			errorMsg(req, "密码错误");
			forwardLogin(req, resp);
			return;
		}
		// 登录成功
		// 创建会话Session
		authkey = sessionManager.createSession(userInfo.getId());
		// 获取会话
		HttpSession session = req.getSession();
		session.setAttribute(CommonConstants.SERVICE_REQUEST_HEADER_UID,
				userInfo.getId().toString());
		session.setAttribute(CommonConstants.SERVICE_REQUEST_HEADER_AUTHKEY,
				authkey);
		UserContext.setCurrentUser(userInfo);
		forwardIndex(req, resp);
	}

	public void forwardIndex(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 这时跳转到index.jsp 根据session生成cookie
		AuthCookieEditor.saveCookie(request, response);
		String returnUrl = request.getParameter("returnUrl");
		if (StringUtils.isNotBlank(returnUrl)) {
			logger.info(LogCategory.SYSTEM, "URL转向到："+returnUrl);
			request.setAttribute("returnUrl", URLDecoder.decode(returnUrl, BaseGroupShareContants.SYSTEM_CHAERSET));
			request.getRequestDispatcher("/WEB-INF/pages/sso.jsp").forward(request, response);
		} else {
			request.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(request, response);
		}
	}

	public void forwardLogin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String returnUrl = request.getParameter("returnUrl");
		if (StringUtils.isNotBlank(returnUrl)) {
			request.setAttribute("returnUrl", URLDecoder.decode(returnUrl, BaseGroupShareContants.SYSTEM_CHAERSET));
		}
		request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request, response);
	}

	public void errorMsg(HttpServletRequest request, String errorMsg) {
		request.setAttribute("errorMsg", errorMsg);
	}
}
